﻿package com.hodgedev.net.drupal 
{
	import flash.errors.IllegalOperationError;
	import flash.net.NetConnection;
	import flash.net.Responder;
	
	/**
	 * ...
	 * @author Brian Hodge
	 */
	public class Views extends Service
	{
		private static const VIEWS_GET:String = "views.get";
		private var _viewResponder:Responder;
		private var _viewName:String;

		public var data:Array;
		
		public function Views(pServices:Services):void
		{
			if (pServices == null) throw new IllegalOperationError("A valid session id must be passed.  Make sure you are connected and pass the key.");
			
			_services = pServices;
			_sessid = _services.sessid;
			_nc = _services.netConnection;
			
			_viewResponder = new Responder(_onViewSuccess, _onViewError);
		}
		private function _onViewSuccess(pArray:Array):void
		{
			data = pArray;
			dispatchEvent(new ViewsEvent(ViewsEvent.VIEW_READY, pArray));
			closeConnection();
		}
		private function _onViewError(pObject:Object):void
		{
			for each (var item:* in pObject)
			{
				trace(item);
			}
			closeConnection();
		}
		public function getView(pViewName:String):void
		{
			_viewName = pViewName;
			if (_checkServiceConnected()) _nc.call(Views.VIEWS_GET, _viewResponder, _sessid, pViewName);
		}
		public override function onConnect(e:ServicesEvent):void
		{
			_services.removeEventListener(ServicesEvent.SYSTEM_CONNECTED, onConnect);
			_nc = _services.netConnection;
			_sessid = _services.sessid;
			
			getView(_viewName);
		}		
	}
}